package com.ywh.train;

import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.htmlparser.Attribute;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.ywh.train.bean.Passenger;
import com.ywh.train.bean.TrainQueryInfo;

public class Util {
    private static Map<String, String> cityName2Code = new HashMap<String, String>();
    static {
        String city[] = Constants.CITYS.split("@");
        for (String tmp : city) {
            if (tmp.isEmpty())
                continue;
            String temp[] = tmp.split("\\|");
            cityName2Code.put(temp[1], temp[2]);
        }
    }
    public final static String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_PART_FORMAT = "yyyy-MM-dd";
    public static final String TIME_PART_FORMAT = "HH:mm:ss.SSS";

    public final static DateFormat default_date_format = new SimpleDateFormat(DATE_PART_FORMAT);

    /**
     * 返回当前日期时间
     * 
     * @return e.g. 2006-06-06 12:12:50
     */
    public static String getCurDateTime() {
        return getCurDateTime(DEFAULT_PATTERN);
    }

    /**
     * 返回当前日期
     * 
     * @return e.g. 2006-06-06
     */
    public static String getCurDate() {
        return getCurDateTime(DATE_PART_FORMAT);
    }

    /**
     * 根据给定的格式返回当前日期或时间
     * 
     * @param formatStr
     * @return
     */
    public static String getCurDateTime(String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        String now = sdf.format(new Date());
        return now;
    }

    public static String getCityCode(String cityName) {
        return cityName2Code.get(cityName);
    }

    /**
     * 查询返回字符对象化
     * 
     * @param response
     * @return
     */
    public static List<TrainQueryInfo> parserQueryInfo(String response) {
        List<TrainQueryInfo> tqis = new ArrayList<TrainQueryInfo>();
        response = response.replaceAll("&nbsp;", "");
        String[] tran_st = response.split(",<span");
        String beginStr = "onclick=javascript:getSelected('";
        String endStr = "')>预订";
        for (int i = 1; i < tran_st.length; i++) {
        	int beginIndex = tran_st[i].indexOf(beginStr);
        	if(beginIndex == -1) {
                //TrainQueryInfo tqi = new TrainQueryInfo();
	            //tqi.setFromStationNo(item[9]);
	            //tqi.setToStationNo(item[10]);
                //tqi.setMmStr("O*****0000M*****0044P*****0006");
        		//tqi.setYpInfoDetail("0EFEA3D2CC280C3FB7F03734D3035A5BE38C42DE15EED27E8B3E4233");
        		//tqi.setLocationCode("Q6");
        		// TODO
        		continue;
        	}
        	beginIndex = beginIndex+beginStr.length();
        	int endIndex = tran_st[i].indexOf(endStr);
        	String tran_st_i = tran_st[i].substring(beginIndex, endIndex);
        	String[] item = tran_st_i.split("#");
        	String[] st = tran_st[i].split(",");
            TrainQueryInfo tqi = new TrainQueryInfo();
            String info1 = "<span" + st[0];
	        try {
	            parserSpan(info1, tqi);
	
	            String temp2[] = st[1].split("<br>");
	            if (temp2[0].startsWith("<img")) {
	                tqi.setFromStation(temp2[0].split(">")[1]);
	            } else {
	                tqi.setFromStation(temp2[0]);
	            }
	            tqi.setStartTime(temp2[1]);
	            String temp3[] = st[2].split("<br>");
	            if (temp3[0].startsWith("<img")) {
	                tqi.setToStation(temp3[0].split(">")[1]);
	            } else {
	                tqi.setToStation(temp3[0]);
	            }
	            tqi.setEndTime(temp3[1]);
	            tqi.setLishi(st[3]);
	            tqi.setBuss_seat(parserFont(st[4]));
	            tqi.setBest_seat(parserFont(st[5]));
	            tqi.setOne_seat(parserFont(st[6]));
	            tqi.setTwo_seat(parserFont(st[7]));
	            tqi.setVag_sleeper(parserFont(st[8]));
	            tqi.setSoft_sleeper(parserFont(st[9]));
	            tqi.setHard_sleeper(parserFont(st[10]));
	            tqi.setSoft_seat(parserFont(st[11]));
	            tqi.setHard_seat(parserFont(st[12]));
	            tqi.setNone_seat(parserFont(st[13]));
	            tqi.setOther_seat(parserFont(st[14]));

	            tqi.setFromStationNo(item[9]);
	            tqi.setToStationNo(item[10]);
	            tqi.setYpInfoDetail(item[11]);
	            tqi.setMmStr(item[12]);
	            tqi.setLocationCode(item[13]);
	        } catch (ParserException e) {
	            e.printStackTrace();
	        }
	        tqis.add(tqi);
        }
        return tqis;
    }

	public static List<TrainQueryInfo> filterByStartEndTime(List<TrainQueryInfo> allTrain, String startTime, String endTime, String trainCodeMatch, String blackTrainCodes, String seatTypes) {
		int startTimeI = 0;
		int endTimeI = 0;
		String[] blackTrains = (blackTrainCodes == null)? new String[]{}:blackTrainCodes.split("\\|");
		String[] seats = (seatTypes == null)? new String[]{}:seatTypes.split("\\|");
		if (null != startTime && !"".equals(startTime)) {
			try {
				startTimeI = Integer.parseInt(startTime);
			} catch (NumberFormatException e) {
			}
		}
		if (null != endTime && !"".equals(endTime)) {
			try {
				endTimeI = Integer.parseInt(endTime);
			} catch (NumberFormatException e) {
			}
		}
		List<TrainQueryInfo> tqis = new ArrayList<TrainQueryInfo>();
        for(TrainQueryInfo  trainQueryInfo: allTrain) {
        	boolean needTrain = true;
        	String startTimeStr = trainQueryInfo.getStartTime();
        	String endTimeStr = trainQueryInfo.getEndTime();
			int startTimeIi = 0;
			int endTimeIi = 0;
			if (null != startTimeStr && !"".equals(startTimeStr)) {
				try {
					startTimeIi = Integer.parseInt(startTimeStr.split(":")[0]);
				} catch (NumberFormatException e) {
				}
			}
			if (null != endTimeStr && !"".equals(endTimeStr)) {
				try {
					endTimeIi = Integer.parseInt(endTimeStr.split(":")[0]);
				} catch (NumberFormatException e) {
				}
			}
			// 开始时间点
			if (needTrain && startTimeI != 0 && startTimeIi != 0 && startTimeIi < startTimeI) {
				needTrain = false;
			}
			// 结束时间点
			if(needTrain && endTimeI != 0 && endTimeIi != 0 && endTimeIi >= endTimeI) {
				needTrain = false;
			}
			// 车次匹配
			if(needTrain && trainCodeMatch != null && !"".equals(trainCodeMatch) && !trainQueryInfo.getTrain_code().startsWith(trainCodeMatch)) {
				needTrain = false;
			}
			// 黑名单(车次过滤)
			if(needTrain && blackTrains.length > 0) {
				for(String blackTrain : blackTrains) {
					if(trainQueryInfo.getTrain_code().equals(blackTrain)) {
						needTrain = false;
						break;
					}
				}
			}
			// 座次匹配
			if(needTrain && seats.length > 0) {
				boolean flag = false;
				for (String seat : seats) {
					if (Constants.getTrainSeat(trainQueryInfo.getTwo_seat()) > 0 && Constants.getTrainSeatName(Constants.TWO_SEAT).startsWith(seat)) {
						flag = true;
						break;
					}
					if (Constants.getTrainSeat(trainQueryInfo.getOne_seat()) > 0 && Constants.getTrainSeatName(Constants.ONE_SEAT).startsWith(seat)) {
						flag = true;
						break;
					}
					if (Constants.getTrainSeat(trainQueryInfo.getSoft_sleeper()) > 0 && Constants.getTrainSeatName(Constants.SOFT_SLEEPER).startsWith(seat)) {
						flag = true;
						break;
					}
					if (Constants.getTrainSeat(trainQueryInfo.getSoft_seat()) > 0 && Constants.getTrainSeatName(Constants.SOFT_SEAT).startsWith(seat)) {
						flag = true;
						break;
					}
					if (Constants.getTrainSeat(trainQueryInfo.getHard_sleeper()) > 0 && Constants.getTrainSeatName(Constants.HARD_SLEEPER).startsWith(seat)) {
						flag = true;
						break;
					}
					if (Constants.getTrainSeat(trainQueryInfo.getHard_seat()) > 0 && Constants.getTrainSeatName(Constants.HARD_SEAT).startsWith(seat)) {
						flag = true;
						break;
					}
				}
				if(!flag) {
					needTrain = false;
				}
			}
			if(needTrain) {
				tqis.add(trainQueryInfo);
			}
        }
		return tqis;
	}

    /**
     * 解析font节点
     * 
     * @param font
     * @return
     * @throws ParserException
     */
    private static String parserFont(String font) throws ParserException {
        String ans = font;
        if (font.startsWith("<font")) {
            int beginIndex = font.indexOf("'>");
            int endIndex = font.indexOf("</");
            ans = font.substring(beginIndex + 2, endIndex);
        }

        return ans;
    }

    /**
     * 解析span节点
     * 
     * @param responseBody
     * @param tqi
     * @throws ParserException
     */
    private static void parserSpan(String responseBody, final TrainQueryInfo tqi) throws ParserException {
        Parser parser = new Parser();
        parser.setInputHTML(responseBody);
        NodeVisitor visitor = new NodeVisitor() {
            public void visitTag(Tag tag) {
                tqi.setTrain_code(tag.getChildren().toHtml());
                Vector<?> atts = tag.getAttributesEx();
                for (int i = 0; i < atts.size(); i++) {
                    Attribute att = (Attribute) atts.get(i);
                    String name = att.getName();
                    if ("onmouseover".equals(name)) {
                        String temp[] = att.getValue().split("'");
                        String subTemp[] = temp[1].split("#");
                        tqi.setTrain_no(subTemp[0]);
                        tqi.setFromStationCode(subTemp[1]);
                        tqi.setToStationCode(subTemp[2]);
                    }
                }
            }
        };
        parser.visitAllNodesWith(visitor);
    }

    /**
     * 移除html标签
     * 
     * @param content
     * @return
     */
    public static String removeTagFromHtml(String content) {
        // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
        String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
        // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
        String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
        // 定义HTML标签的正则表达式
        String regEx_html = "<[^>]+>";

        String temp = content;
        if (content == null || content.isEmpty()) {
            return "ERROR: Content is empty!";
        }
        // 去除js
        temp = temp.replaceAll(regEx_script, "");
        // 去除style
        temp = temp.replaceAll(regEx_style, "");
        // 去除html
        temp = temp.replaceAll(regEx_html, "");
        // 去除空格
        temp = temp.replaceAll("&nbsp;", " ");
        // 合并空格
        temp = temp.replaceAll("\\s+", " ");

        return temp.trim();
    }

    public static String getMessageFromHtml(String content) {
        String regEx_msg = "[\\s]*?var\\s+message\\s+=\\s+\"([\\S]*?)\"";
        String temp = content.trim();
        Pattern p = null;
        Matcher m = null;
        p = Pattern.compile(regEx_msg);
        m = p.matcher(temp);
        try {
            while (m.find()) {
                temp = m.group(1);
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static int getHour2Min(String hour) {
        int min = 0;
        String hm[] = hour.split(":");
        if (hm.length < 2) {
            min = Integer.parseInt(hour);
        } else {
            int h = Integer.parseInt(hm[0]) * 60;
            int m = Integer.parseInt(hm[1]);
            min = h + m;
        }
        return min;
    }

    /**
     * 选座算法
     * 
     * @param train
     * @return
     */
    public static String getSeatAI(TrainQueryInfo train) {
        if (Constants.getTrainSeat(train.getTwo_seat()) > 0) {
            return Constants.TWO_SEAT;
        }

        if (Constants.getTrainSeat(train.getOne_seat()) > 0) {
            return Constants.ONE_SEAT;
        }

        if (Constants.ISHARDSLEEPFIRST) {
            if (Constants.getTrainSeat(train.getHard_sleeper()) > 0) {
                return Constants.HARD_SLEEPER;
            }
        }

        if (Constants.getTrainSeat(train.getHard_seat()) > 0) {
            return Constants.HARD_SEAT;
        }

        if (Constants.getTrainSeat(train.getHard_sleeper()) > 0) {
            return Constants.HARD_SLEEPER;
        }

        if (Constants.getTrainSeat(train.getNone_seat()) > 0) {
            if (train.getTrain_no().startsWith(Constants.TRAIN_D)) {
                return Constants.TWO_SEAT;
            }
            return Constants.HARD_SEAT;
        }
        return null;
    }

    public static void waitMoment(long mi) {
        try {
            Thread.sleep(mi);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String formatInfo(String info) {
        return getCurDateTime() + " : " + info + "\n";
    }

	public static Map<String, String> jsonToMap(String json) {
		Map<String, String> map = new HashMap<String, String>();
		String jsonStr = json.replaceAll("[{\"}]", "");
		String[] key_val = jsonStr.split(",");
		for (int i = 0; i < key_val.length; i++) {
			String[] key_vali = key_val[i].split(":");
			if(key_vali.length==1) {
				map.put(key_vali[0], "");
			} else {
				map.put(key_vali[0], key_vali[1]);
			}
		}
		return map;
	}

    public static List<Passenger> parsePassengerJson(String passengerJson) throws IllegalAccessException, InvocationTargetException {
        List<Passenger> passengers = new ArrayList<Passenger>(); 
        //String passengerJson = "{\"passengerJson\":[{\"first_letter\":\"FBZ\",\"isUserSelf\":\"\",\"mobile_no\":\"13016394187\",\"old_passenger_id_no\":\"\",\"old_passenger_id_type_code\":\"\",\"old_passenger_name\":\"\",\"passenger_flag\":\"0\",\"passenger_id_no\":\"430423196503078242\",\"passenger_id_type_code\":\"1\",\"passenger_id_type_name\":\"\",\"passenger_name\":\"刘春秀\",\"passenger_type\":\"1\",\"passenger_type_name\":\"\",\"recordCount\":\"3\"},{\"first_letter\":\"ZJ\",\"isUserSelf\":\"\",\"mobile_no\":\"13016394187\",\"old_passenger_id_no\":\"\",\"old_passenger_id_type_code\":\"\",\"old_passenger_name\":\"\",\"passenger_flag\":\"0\",\"passenger_id_no\":\"430423198710160926\",\"passenger_id_type_code\":\"1\",\"passenger_id_type_name\":\"\",\"passenger_name\":\"周娟\",\"passenger_type\":\"1\",\"passenger_type_name\":\"\",\"recordCount\":\"3\"},{\"first_letter\":\"FXH\",\"isUserSelf\":\"\",\"mobile_no\":\"13016394187\",\"old_passenger_id_no\":\"\",\"old_passenger_id_type_code\":\"\",\"old_passenger_name\":\"\",\"passenger_flag\":\"0\",\"passenger_id_no\":\"430423198811128212\",\"passenger_id_type_code\":\"1\",\"passenger_id_type_name\":\"\",\"passenger_name\":\"范晓辉\",\"passenger_type\":\"1\",\"passenger_type_name\":\"\",\"recordCount\":\"3\"}]";
        passengerJson = passengerJson.substring("{\"passengerJson\":[{".length());
        passengerJson = passengerJson.substring(0, passengerJson.length() - "}]".length());
        //System.out.println(passengerJson);
        String[] passengerStrings = passengerJson.split("\\},\\{");
        for (String passengerStr : passengerStrings) {
            Map<String, String> map = Util.jsonToMap(passengerStr);
            Passenger passenger = new Passenger();
            BeanUtils.copyProperties(passenger, map);
            //System.out.println(passenger.getPassenger_id_no());
            passengers.add(passenger);
        }
        return passengers;
    }
	
    public static Map<String, Passenger> genPassengerMap(List<Passenger> passengers) {
        Map<String, Passenger> passengerMap = new HashMap<String, Passenger>();
        if(passengers != null) {
            for(int i = 0,j = passengers.size(); i < j; i++) {
                Passenger passenger = passengers.get(i);
                passenger.setOrderno(String.valueOf(i));
                passengerMap.put(passenger.getPassenger_id_no(), passenger);
            }
        }
        return passengerMap;
    }
    
	public static String getTicketCountDesc(String mark,String seat){
		String rt = "";
		int seat_1 = -1;
		int seat_2 = -1;
		int i = 0;
		while (mark != null && i < mark.length()) {
			String s = mark.substring(i, i + 10);
			String c_seat = s.substring(0, 0 + 1);
			if (c_seat != null && c_seat.equals(seat)) {
				String count = s.substring(6,6 + 4);
				while(count != null && count.length()>1 && "0".equals(count.substring(0,0 + 1))){
					count = count.substring(1, count.length());
				}
				int countNo = Integer.parseInt(count);
				if(countNo<3000){
					seat_1=countNo;
				}else{
					seat_2=(countNo-3000);
				}
			}
			i = i+10;
		}
		
		if(seat_1>-1){
			rt += "[" + seat_1 + "]张";
		}
		if(seat_2>-1){
			rt += ",无座[" + seat_2+"]张";
		}
		return rt;
	}
    
    // 首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    // 首字母转大写
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }
}
